package com.sky.cqculture.Contraller;

import com.sky.cqculture.pojo.Result;
import com.sky.cqculture.pojo.ShoppingCart;
import com.sky.cqculture.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class ShoppingCartController {
    
    @Autowired
    private ShoppingCartService shoppingCartService;
    
    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public Result addToCart(@RequestParam Integer userId, @RequestParam Integer productId, @RequestParam(defaultValue = "1") Integer quantity) {
        try {
            ShoppingCart cartItem = shoppingCartService.addToCart(userId, productId, quantity);
            return Result.success("商品添加成功");
        } catch (Exception e) {
            return Result.error("添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取购物车商品列表
     */
    @GetMapping("/list")
    public Result getCartItems(@RequestParam Integer userId) {
        try {
            List<ShoppingCart> cartItems = shoppingCartService.getCartItems(userId);
            return Result.success(cartItems);
        } catch (Exception e) {
            return Result.error("获取购物车失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新购物车商品数量
     */
    @PostMapping("/update")
    public Result updateCartItemQuantity(@RequestParam Integer userId, @RequestParam Integer productId, @RequestParam Integer quantity) {
        try {
            ShoppingCart cartItem = shoppingCartService.updateCartItemQuantity(userId, productId, quantity);
            return Result.success("更新成功");
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除购物车商品
     */
    @DeleteMapping("/delete")
    public Result removeCartItem(@RequestParam Integer userId, @RequestParam Integer cartId) {
        try {
            shoppingCartService.removeCartItem(userId, cartId);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 清空购物车
     */
    @DeleteMapping("/clear")
    public Result clearCart(@RequestParam Integer userId) {
        try {
            shoppingCartService.clearCart(userId);
            return Result.success("购物车已清空");
        } catch (Exception e) {
            return Result.error("清空失败：" + e.getMessage());
        }
    }
}